package com.zegome.game.gomestory.main.scene.chapter;
import android.text.style.LineHeightSpan.WithDensity;
import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent;
import com.zegome.facebook.IFacebookBridge;
import com.zegome.game.gomestory.main.D;
import com.zegome.game.gomestory.main.helper.IMAction;
import com.zegome.game.gomestory.main.scene.BaseGameScreen;
import com.zegome.game.gomestory.main.scene.level.LevelScreen;
import com.zegome.game.main.AndroidGameController;
import com.zegome.game.screen.GameScreenOption;
import com.zegome.game.util.helper.WidgetAccessor;

public class ChapterScreen extends BaseGameScreen {	
	
	private Image bg;	
	
	private Table chapterTable;
	private ScrollPane chapterScroll;
	
	private int currentChapter = 1;
	private float current = 0;
	private float[] leftCurrent={0,471,942,1377,1812, 2283,2714,3147};
	private float beforePercent, afterPercent, currentPercent;
	private int[] wiPika = {471,471,471, 399, 471, 471,391, 476};
	private int wiTable=3947;
	private Image[] pika;
	private Image[] lock;
	private float delta = 0.6f;
	private boolean isFinish = true;
	
	public ChapterScreen(AndroidGameController controller, String name, final IFacebookBridge bridge) {
		super(controller, name,bridge);		
		setConfig(true, true, true,true);		
	}
	
	
	public void show()
	{
		ctr.a.soundOnOff();
		ctr.a.isHasDialog.removeAllElements();
		ctr.d.backLis.removeAllElements();
		state = 0;
		stage.clear();
		createUi();
		super.show();		
		if(ctr.d.passScreen[D.GAME] == false){
			ctr.d.passScreen[D.GAME] = true;
			ctr.d.saveAccount();
		}
		ctr.a.bgSong.play();
	}	
	
	public void createUi()
	{
		
		ctr.d.getDataChapter();
				
		if(bg==null){
			bg = ctr.stageHelper.createImage(ctr.a.bgCommondRegion, 0, 0, (800), (480));
		}
		
		//addIconGomeSmallStage();
		
		
		stage.addActor(bg);		
		addIconGomeSmallStage();		
		createChapterScroll();
		Table avatar = ctr.stageHelper.createAvatar(this,stage, tweenManager, (0), (480-99), 1f);
		stage.addActor(avatar);
		
		currentChapter = 1;
		
		pika[0].setScale(1.0f);
	}
	
	public void createChapterScroll(){
		lock = null;
		
		lock = new Image[8];
		pika = new Image[8];
		
		if(chapterTable!=null){
			chapterTable.remove();
			chapterTable.clear();
			chapterTable = null;
		}
		
		
		if(chapterScroll != null){
			chapterScroll.remove();
			chapterScroll.clear();
			chapterScroll = null;
		}
		int xBegin = 164;
		if(chapterTable == null){
			chapterTable = ctr.stageHelper.createTableWithTransBg(ctr.g.mSkin, 0, 0, wiTable, 412);			
			
			Table table = createChapterTable(7);
			table.setPosition(xBegin, 0);
			chapterTable.addActor(table);
			xBegin += wiPika[0];
			
			for(int i=0;i<7;i++){
				Table _table = createChapterTable(i);
				_table.setPosition(xBegin, 0);
				chapterTable.addActor(_table);
				xBegin += wiPika[i+1];
			}
		}
		
		if(chapterScroll == null){
			chapterScroll = new ScrollPane(chapterTable);
			chapterScroll.setBounds((0), (480-412)/2, (800), (412));
		}
		
		chapterScroll.setFlingTime(0);
		
		stage.addActor(chapterScroll);
	}
	
	public Table createChapterTable(final int index)
	{
		TextureRegion pikaRegion = ctr.d.chapters[index].unlock;
		int indexView = (index==7?0:(index+1));
		float wiContent=0;
		Table table = null;
		ImageButton imgBut;
		if(table == null){
			table = ctr.stageHelper.createTableWithTransBg(ctr.g.mSkin, 0, 0, wiPika[indexView], (412));			
			imgBut = ctr.stageHelper.createImageButton(ctr.g.mSkin, ctr.a.transRegion, ctr.a.transRegion, ctr.a.transRegion, 0, 0, wiPika[indexView],412);
			pika[indexView] = ctr.stageHelper.createImage(pikaRegion, ((wiPika[indexView]-pikaRegion.getRegionWidth())/2), ((412-pikaRegion.getRegionHeight())/2),(pikaRegion.getRegionWidth()),(pikaRegion.getRegionHeight()));						
			pika[indexView].setOrigin(pikaRegion.getRegionWidth()/2, pikaRegion.getRegionHeight()/2);			
			if(ctr.d.chapters[index].isUnLock == false){
				pika[indexView].setColor(0.5f, 0.5f, 0.5f, 1f);				
			}
			final int indexChapter = index;
			imgBut.addListener( new ChangeListener() {
				@Override
				public void changed (ChangeEvent event, Actor actor) {
					if(ctr.a.isHasDialog() == true)
						return;
					if(state != 1)
						return;
					ctr.a.yesSound.play(ctr.a.vls);
					if(ctr.d.chapters[index].isUnLock == true||ctr.d.isTestVersion){
						fadeOut(new TweenCallback() {							
							@Override
							public void onEvent(int arg0, BaseTween<?> arg1) {
								// TODO Auto-generated method stub
								ctr.a.bgSong.pause();	
								ctr.a.clearChapter();
								ctr.a.loadedLevel();
								clear();
								LevelScreen.GAME_CHAPTER = indexChapter;
														
								mController.setScreen(mController.getScreen("LevelScreen"));
							}
						});
					}
					else{
						if(ctr.d.chapters[index-1].isUnLock == true){
						ctr.stageHelper.createDialog(getStage(), getTween(), ctr.lang.getStarToInlock(index, ctr.d.getTotalStarAllChapter()), 2,
								new ChangeListener() {									
									@Override
									public void changed(ChangeEvent arg0, Actor arg1) {
										// TODO Auto-generated method stub
										ctr.stageHelper.createDialogPayGoldDiamond(ChapterScreen.this, stage, tweenManager, 5000,20000,new IMAction() {											
											@Override
											public void action() {
												// TODO Auto-generated method stub
												postRunnable(new Runnable() {
													
													@Override
													public void run() {
														// TODO Auto-generated method stub
														ctr.d.chapters[index].isUnLock = true;
														ctr.d.levels[index].maxLevel = 1;
														ctr.d.saveAllChapter();
														
														createChapterScroll();
														ctr.stageHelper.createDialog(stage, tweenManager, ctr.lang.unlockChapterSuccess, 1, null, null);

													}
												});
																							
											}
										});
									}
								}, null);
					}
						else{
							ctr.stageHelper.createDialog(getStage(), getTween(), ctr.lang.getNotCompleteChapter(), 1,
									null, null);
						}
					}
				}
			});

			table.addActor(pika[indexView]);
			if(ctr.d.chapters[index].isUnLock == false){
				lock[indexView] = ctr.stageHelper.createImage(ctr.a.iconLockChapterRegion, (wiPika[indexView]-117)/2, (412-113)/2);
				lock[indexView].setOrigin(59, 54);
				table.addActor(lock[indexView]);
			}
			Label number = ctr.stageHelper.createLabel(ctr.g.mFontCombo, "", Color.WHITE, 0, 0);
			//number.setText(""+(ctr.d.chapters[index].isUnLock?ctr.d.chapters[index].starCollect:ctr.d.chapters[index].starToUnLock));
			number.setText(""+(ctr.d.chapters[index].isUnLock?"":ctr.d.chapters[index].starToUnLock));

			number.setScale(1f);
			number.setPosition(0, 30);
			float xStar = number.getX()+number.getTextBounds().width+5;
			Image star = ctr.stageHelper.createImage(ctr.a.starRegion, xStar, (0));			
			table.addActor(number);
			if(ctr.d.chapters[index].isUnLock == false)
				table.addActor(star);
			table.addActor(imgBut);
			if(ctr.d.chapters[index].isUnLock == false)
				wiContent = star.getX()+star.getWidth() - (0);
			else{
				wiContent = star.getX()+star.getWidth() - (0);				
			}
			float deltaX = ((ctr.d.chapters[index].unlock.getRegionWidth())-wiContent)/2-(0);
			setActorPos(number, deltaX);
			setActorPos(star, deltaX);
			if(indexView!=0)
			pika[indexView].setScale(delta);			
		}
		return table;
	}
	
	public void setActorPos(Actor actor, float deltaX){
		if(actor != null)
			actor.setX(actor.getX()+deltaX);
	}

	public void onManagedUpdate(float pDeltaTime)
	{
		update(pDeltaTime);
		
		if(state == 1 && chapterScroll!=null){
			current = chapterScroll.getScrollX();
			if(currentChapter>=2&&current<leftCurrent[currentChapter-1]){				
				if(current>leftCurrent[currentChapter-2]){					
					beforePercent = 1- (current - leftCurrent[currentChapter-2])/(leftCurrent[currentChapter-1]-leftCurrent[currentChapter-2]);
					currentPercent = 1-beforePercent;
					
					pika[currentChapter-1].setScale(delta+(1-delta)*currentPercent);
					if(lock[currentChapter-1]!=null){
						lock[currentChapter-1].setScale(delta+(1-delta)*currentPercent);
					}					
					pika[currentChapter-1].setColor(pika[currentChapter-1].getColor().r,pika[currentChapter-1].getColor().g,pika[currentChapter-1].getColor().b,delta+(1-delta)*currentPercent);					
					
					pika[currentChapter-2].setScale(delta+(1-delta)*beforePercent);					
					pika[currentChapter-2].setColor(pika[currentChapter-2].getColor().r,pika[currentChapter-2].getColor().g,pika[currentChapter-2].getColor().b,delta+(1-delta)*beforePercent);
					if(lock[currentChapter-2]!=null){
						lock[currentChapter-2].setScale(delta+(1-delta)*beforePercent);
					}
				}
				else if(current <= leftCurrent[currentChapter-2]){
					currentChapter--;
					
					return;
				}
				
			}
			else if(currentChapter<=(leftCurrent.length-1)&&current>leftCurrent[currentChapter-1]){	
				if(current<leftCurrent[currentChapter]){					
					afterPercent = 1- (leftCurrent[currentChapter]-current)/(leftCurrent[currentChapter]-leftCurrent[currentChapter-1]);
					currentPercent = 1-afterPercent;
					
					pika[currentChapter-1].setScale(delta+(1-delta)*currentPercent);
					pika[currentChapter-1].setColor(pika[currentChapter-1].getColor().r,pika[currentChapter-1].getColor().g,pika[currentChapter-1].getColor().b,delta+(1-delta)*currentPercent);
					if(lock[currentChapter-1]!=null){
						lock[currentChapter-1].setScale(delta+(1-delta)*currentPercent);
					}
					
					pika[currentChapter].setScale(delta+(1-delta)*afterPercent);
					pika[currentChapter].setColor(pika[currentChapter].getColor().r,pika[currentChapter].getColor().g,pika[currentChapter].getColor().b,delta+(1-delta)*afterPercent);
					if(lock[currentChapter]!=null){
						lock[currentChapter].setScale(delta+(1-delta)*afterPercent);
					}
				}
				else if(current>=leftCurrent[currentChapter]){
					currentChapter++;
					return;
				}
			}
			if(chapterScroll.isDragging() || chapterScroll.isPanning() || chapterScroll.isFlinging()){				
			}
			else{
				if(current==leftCurrent[currentChapter-1]){
				}
				else{
					if (isFinish == true) {
						if (currentChapter >= 2
								&& current < leftCurrent[currentChapter - 1]) {
							Tween.to(chapterScroll, WidgetAccessor.SCROLL, 0.5f)
									.target(leftCurrent[currentChapter - 2])
									.setCallback(new TweenCallback() {

										@Override
										public void onEvent(int arg0,
												BaseTween<?> arg1) {
											// TODO Auto-generated method stub
											isFinish = true;
										}
									}).start(tweenManager);

							isFinish = false;
						} else if (currentChapter <= (leftCurrent.length-1)
								&& current > leftCurrent[currentChapter - 1]) {
							Tween.to(chapterScroll, WidgetAccessor.SCROLL, 0.5f)
									.target(leftCurrent[currentChapter])
									.setCallback(new TweenCallback() {

										@Override
										public void onEvent(int arg0,
												BaseTween<?> arg1) {
											// TODO Auto-generated method stub
											isFinish = true;
										}
									}).start(tweenManager);
							isFinish = false;
						}
					}
				}		
			}
		}					
		super.onManagedUpdate(pDeltaTime);
	}	
	
	public void backKeyProcess(){
		//postRunnable(new Runnable() {
			
		//	@Override
		//	public void run() {
				// TODO Auto-generated method stub
				fadeOut(new TweenCallback() {			
					@Override
					public void onEvent(int arg0, BaseTween<?> arg1) {
						// TODO Auto-generated method stub
						ctr.a.bgSong.pause();
						ctr.a.loadedMenu();
						ctr.a.clearChapter();
						clear();
						mController.setScreen(mController.getScreen("MenuScreen"));
					}
				});
		//	}
		//});		
	}
	
	public void clear(){
		super.clear();
		bg = null;	
		chapterTable = null;
		chapterScroll = null;
		pika = null;
	}
	
}
